package com.zh.note.demo.juc;

import com.zh.note.thread.ThreadPoolFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Author: zhanghuan
 * @date: 2023/4/2 10:50
 * @description: create it
 */
public class CountDownLatchDemo {

    private static final Logger LOGGER = LoggerFactory.getLogger(CountDownLatchDemo.class);

    private static final ThreadPoolExecutor threadPoolExecutor = ThreadPoolFactory.newThreadPoolExecutor("microwave",
            10, 10, 1000);

    public String batchAdd(int number) {
        CountDownLatch countDownLatch = new CountDownLatch(number);
        CountDownLatchDemo countDownLatchDemo = new CountDownLatchDemo();

        for (int i = 0; i < number; i++) {
            // CompletableFuture.runAsync(this::createDevice, threadPoolExecutor)
            //         .whenComplete((v, throwable) -> countDownLatch.countDown());
            int finalI = i;
            CompletableFuture.runAsync(() -> {
                        countDownLatchDemo.createDevice(finalI);
                    }, threadPoolExecutor)
                    .whenComplete((v, throwable) -> countDownLatch.countDown());
        }

        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "ok";
    }

    private void createDevice() {
        LOGGER.info("[" + Thread.currentThread().getName() + "]" + "创建设备完成");
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    private void createDevice(int i) {
        LOGGER.info("[" + Thread.currentThread().getName() + "]" + "第" + i + "个设备，创建设备完成");
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        new CountDownLatchDemo().batchAdd(500);
    }

}
